import Mn from 'backbone.marionette';
import { closeModal } from '../../tools.js';


const TabsBehavior = Mn.Behavior.extend({
    /** Tabs behaviour
     *
     * Offers an abstraction layer over BootStrap 3 tabs
     * https://getbootstrap.com/docs/3.3/javascript/#tabs
     *
     * Secret plan: might be the first step for getting rid of bootstrap.
     *
     * For some reason, BS events other than show.bs.tab do not fire
     *
     * This behaviour fires following events:
     *
     *   tab:beforeSelect -> when a tab is about to be selected
     *   tab:beforeDeselect -> when a tab is about to be deselected
     */
    events: {
        'show.bs.tab': '_onBeforeTabSelect',
    },
    options: {
        tabPanes: [],
    },
    onInitialize() {
        for (let tabPane of this.getOption('tabPanes')) {
            let region = this.view.getRegion(tabPane.region);
            if (! region) {
                throw new Error('No such region: ' + tabPane.region);
            }
        }
    },
    /* From the event target on a tab click finds the tab pane region
     *
     * @param target the event target (DOM element)
     * @returns a Marionette Region
     */
    findTabPane(target) {
        let tabPane = this.getOption('tabPanes').find(
            function(tabPane) {
                console.log('CMP', target.getAttribute('aria-controls'), tabPane.id);
                return target.getAttribute('aria-controls') == tabPane.id;
            }
        );
        return this.view.getRegion(tabPane.region);
    },
    _onBeforeTabSelect(e){
        let oldTabRegion = this.findTabPane(e.relatedTarget);
        console.log('TabContainerBehavior: tab pane deselect :', oldTabRegion._name);
        this.view.triggerMethod('tab:beforeDeselect', oldTabRegion);

        let newTabRegion = this.findTabPane(e.target);
        console.log('TabContainerBehavior: tab pane select :', newTabRegion._name);
        this.view.triggerMethod('tab:beforeSelect', newTabRegion);
    },
});
export default TabsBehavior;
